package com.kotodama.infrastructure.tenant.filter;

import jakarta.persistence.EntityManagerFactory;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.context.request.RequestContextListener;

@Configuration
public class TenantFilterConfiguration {

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

    @Bean
    public OpenEntityManagerInViewFilter openEntityManagerInViewFilter() {
        return new OpenEntityManagerInViewFilter();
    }

    /**
     * 启用租户过滤器的工具类
     */
    public static void enableTenantFilter(EntityManagerFactory entityManagerFactory, String tenantId) {
        Session session = entityManagerFactory.createEntityManager().unwrap(Session.class);
        Filter filter = session.enableFilter("tenantFilter");
        filter.setParameter("tenantId", tenantId);
    }

    /**
     * 禁用租户过滤器的工具类（仅供超级管理员等特权操作使用）
     */
    public static void disableTenantFilter(EntityManagerFactory entityManagerFactory) {
        Session session = entityManagerFactory.createEntityManager().unwrap(Session.class);
        session.disableFilter("tenantFilter");
    }
}
